package cn.itcast.algorithm;

/**
 * 二分查找实现求平方根
 * 不断取中间的数越接近于平方根 a*a=a2
 * create by zhangtian3 on 2019/4/9
 */
public class SqrtData {
    public static double sqrt(double  x) {
        double low = 0 ,high = x ;

        while (low <= high){
            double mid = low + (high - low) / 2.0 ;

            if (Math.abs(mid * mid - x) < 0.000001) {
                return mid ;
            }else if(mid * mid < x) {
                low = mid ;
                high = x / mid ;
            }else {
                high = mid ;
                low = x / mid ;
            }
        }

        return low ;
    }
}
